package com.little.wxlogin.util;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.little.wxlogin.Enum.WxApiType;
import com.little.wxlogin.constant.SystemConstant;
import com.little.wxlogin.pojo.ro.AppletsWxLoginRO;
import com.little.wxlogin.pojo.ro.GetWxUserInfoRO;
import com.little.wxlogin.pojo.ro.WxUserInfoRO;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 微信登录工具包
 * @Author 小乌龟
 * @Date 2022/10/30 20:03
 */
@Slf4j
public class WxLoginUtil {
    /**
      *微信登录
      * @param code 前端请求获取=>微信code
      * @return void
      * @author zhangjunrong
      * @date 2022/10/30 20:16
      */
    public static WxUserInfoRO toWxLogin(String code){
        //1.通过前端给的code获取openid和access_token
        String getTokenOpenid = StrFormatter.format(WxApiType.GET_TOKEN_OPENID.getValue(), SystemConstant.APPID,SystemConstant.SECRET, code);
        String data = HttpUtil.get(getTokenOpenid);
        log.info("微信获取获取openid和access_token,返回结果======{}=====",data);
        //json=>bean
        GetWxUserInfoRO getWxUserInfoRO = JSONUtil.toBean(data, GetWxUserInfoRO.class);
        //2.通过access_token和openid获取用户信息
        String getUserInfo = StrFormatter.format(WxApiType.GET_WX_USERINFO.getValue(), getWxUserInfoRO.getAccess_token(), getWxUserInfoRO.getOpenid());
        String userInfoJson = HttpUtil.get(getUserInfo);
        log.info("微信获取用户信息====未转换对象===={}====",userInfoJson);
        WxUserInfoRO userInfo = JSONUtil.toBean(userInfoJson, WxUserInfoRO.class);
        log.info("微信获取用户信息===={}====",userInfo);
        //todo 待完善 用户信息获取失败 抛异常 (为了项目的精简 就不引入全局异常捕获)
        return userInfo;
    }

    /**
     *微信登录
     * @param code 前端请求获取=>微信code
     * @return void
     * @author zhangjunrong
     * @date 2022/12/19 20:16
     */
    public static AppletsWxLoginRO toAppletsWxLogin(String code){
        //1.通过前端给的code获取openid和access_token还有unionid
        String getTokenOpenid = StrFormatter.format(WxApiType.APPLETS_GET_TOKEN_OPENID.getValue(), SystemConstant.APPLETS_APPID,SystemConstant.APPLETS_SECRET, code);
        String data = HttpUtil.get(getTokenOpenid);
        log.info("微信获取获取openid和unionid,返回结果======{}=====",data);
        //json=>bean
        AppletsWxLoginRO getWxUserInfoRO = JSONUtil.toBean(data, AppletsWxLoginRO.class);
        //todo 获取用户信息失败 抛异常
        return getWxUserInfoRO;
    }

}
